package com.zysd.collection.scheduler.service.model.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lensyn.common.utils.domain.common.PageResponse;
import com.zysd.collection.scheduler.condition.PageCondition;
import com.zysd.collection.scheduler.dao.SchedulerTaskTerminalMappingDao;
import com.zysd.collection.scheduler.entity.SchedulerTaskTerminalMapping;
import com.zysd.collection.scheduler.service.model.ModelTerminalMappingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 任务模板与终端关联关系 service
 *
 * @author liuht
 * @date 2017/10/18 11:25
 */
@Service
public class ModelTerminalMappingServiceImpl implements ModelTerminalMappingService {

    @Autowired
    private SchedulerTaskTerminalMappingDao mappingDao;

    @Override
    public PageResponse mappingsByModelId(Long taskModelId, PageCondition condition) {
        PageHelper.offsetPage(condition.getOffset(), condition.getRows());
        List<SchedulerTaskTerminalMapping> models = mappingDao.mappingsByModelId(taskModelId);
        Page<SchedulerTaskTerminalMapping> page = (Page<SchedulerTaskTerminalMapping>) models;
        return new PageResponse<>((int) page.getTotal(), models);
    }

    @Override
    public List<SchedulerTaskTerminalMapping> modelmMappings(Long taskModelId) {
        return mappingDao.mappingsByModelId(taskModelId);
    }

    @Override
    public void addMapping(List<SchedulerTaskTerminalMapping> mappings) {
        for (int i = 0; i < mappings.size(); i++) {
            SchedulerTaskTerminalMapping mapping = mappings.get(i);
            if (mappingDao.existMapping(mapping) == 1) {
                mappings.remove(i);
            }
        }
        if (!CollectionUtils.isEmpty(mappings)) {
            mappingDao.addMapping(mappings);
        }
    }

    @Override
    public void deleteMapping(List<SchedulerTaskTerminalMapping> mappings) {
        for (SchedulerTaskTerminalMapping mapping : mappings) {
            mappingDao.deleteMapping(mapping);
        }
    }
}
